package com.fulihui.weixinsdk.http;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 
 * Created by LeeSon on 2017/3/30 0030.
 */
public class SimpleHttpClient implements HttpInvoke {
    private static final Logger        logger = LoggerFactory.getLogger("HTTPCLIENT_UTIL_LOG");

    PoolingHttpClientConnectionManager cm;
    CloseableHttpClient                httpClient;

    public SimpleHttpClient(int maxTotal, int maxRoute) {
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(maxTotal);// 最大连接数
        cm.setDefaultMaxPerRoute(maxRoute);// 单路由最大连接数
        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }

    @Override
    public String doGet(HttpRequest request) {
        try {
            String fullUrl = HttpUtil.genFullGetUrl(request.getUrl(), request.getParams(), request.getUrlFoot());
            return HttpUtil.executeGet(httpClient, fullUrl);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public String doPost(HttpRequest request) {
        String resp = null;
        try {
            // 如果有请求体，params当作请求参数，否则params当form表单
            if (StringUtils.isBlank(request.getData())) {
                resp = HttpUtil.executePost(httpClient, request.getUrl(), request.getParams());
            } else {
                String fullUrl = HttpUtil.genFullGetUrl(request.getUrl(), request.getParams(), request.getUrlFoot());
                resp = HttpUtil.executePost(httpClient, fullUrl, request.getData());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return resp;
    }

    @Override
    public void close() {
        try {
            if (null != httpClient) {
                httpClient.close();
            }
            if (null != cm) {
                cm.close();
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}